from webbrowser import get
from numpy import less
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from loger import *

# import demjson
import random
import os
import time
import logging
import socket
import pymysql
import pickle
import pathlib
import sqlite3
import uuid
import ddddocr
# logging.basicConfig(level=logging.INFO,format='%(asctime)s -%(levelname)s -%(process)d -%(module)s -%(funcName)s -%(message)s')
root=pathlib.Path(__file__).parent
ocr = ddddocr.DdddOcr()
log = Logger('test',StreamLevel='debug',FileLevel='info')
log=log.logger

global browser
def init(url):
    global browser
    chrome_options = Options()
    # chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")
    chrome_options.add_argument("--ignore-certificate-errors")
    chrome_options.binary_location=r"D:\chrome-win64\chrome.exe"
    service=Service(str(root/"chromedriver.exe"))
    browser = webdriver.Chrome(service=service, options=chrome_options)
    # browser = webdriver.Chrome(options=chrome_options)
    browser.get(url)
    browser.maximize_window()
    browser.implicitly_wait(15)
    return browser

def findxpath(xpath,t=3):
    global browser
    browser.implicitly_wait(t)
    try:
        result = browser.find_element(By.XPATH,xpath)
    except :
        log.info("not find xpath!")
        result= None

    return result
def findlinktext(text,t=5):
    global browser
    browser.implicitly_wait(t)
    try:
        result = browser.find_element(By.LINK_TEXT,text)
    except :
        log.info("not find xpath!")
        result= None
    return result
def clickobj(obj):
    global browser
    actions = ActionChains(browser)
    actions.move_to_element(obj)
    actions.click(obj)
    actions.perform()
def getShortId():
    array = ["a", "b", "c", "d", "e", "f",
         "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
         "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5",
         "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I",
         "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
         "W", "X", "Y", "Z"]
    id = str(uuid.uuid4()).replace("-", '')
    buffer = []
    for i in range(8):
        start = i * 4
        end = i * 4 + 4
        val = int(id[start:end], 16)
        buffer.append(array[val % 62])
    return "".join(buffer)
def waitElement(xpath,waittime=10):
    try:
        WebDriverWait(browser,waittime).until(EC.visibility_of_element_located((By.XPATH,xpath)))
    except:
        return False
    else:
        return True
def switch2nowPage():

    handles = browser.window_handles
    try:
        # browser.switch_to_window(handles[len(handles)-1])
        browser.switch_to.window(browser.window_handles[-1])
    except Exception as e:
        log.exception(e)
        log.error('switch_to_window error!')

def getjson(url):
    js= f"mytemp=$.get(\"{url}\");"  
    jsobj=tjs(js)
    js= f"return mytemp.responseText;"  
    time.sleep(0.2)
    jsobj=tjs(js)
    jsobj=demjson.decode(jsobj)
    return jsobj
def tryclick(xpath):
    try:
        browser.find_element(By.XPATH,xpath).click()
    except:
        log.error("点击失败")
    else:
        log.info("点击成功")

def tjs(js):
    try:
        obj = browser.execute_script(js)
    except:
        log.error(f"执行失败 {js}")
        return False
    else:
        log.info(js+"js_ok")
        return obj

def getcodes(imgxpath):
    codes=None
    id=getShortId()
    time.sleep(1)
    if(not waitElement(imgxpath)):
        return False
    try:
        img1=browser.find_element(By.XPATH,imgxpath)
        img1.screenshot(id+'.jpg')
    except:
        log.info("getcodes error")
    else:
        im = open(id+'.jpg', 'rb').read()

        # browser.find_element(By.XPATH,'//*[@id="popLogin"]/div/form/div[5]/div[1]/input').clear()
        # codes = chaojiying.PostPic(im, 1004) 
        # codes = chaojiying.PostPic(im, 8001)  #体验包（1元/24小时 500次）
        # print(codes)
        # codes=codes['pic_str']
        codes = ocr.classification(im)
        logging.info(codes)
        # browser.find_element(By.XPATH,'//*[@id="popLogin"]/div/form/div[5]/div[1]/input').send_keys(codes)
        # driver.find_element(By.XPATH,'//*[@id="popLogin"]/div/form/div[4]/div[1]/input').send_keys('pic_str')
        os.remove(id+'.jpg')
        return codes

def savecookies():
    global browser
    pickle.dump(browser.get_cookies(), open(str(root/"cookies.tmp"),"wb"))

def loadcookies():
    try:
        cookies = pickle.load(open(str(root/"cookies.tmp"), "rb"))
        for cookie in cookies:
            browser.add_cookie(cookie)
            log.debug(f"set cookie ---> {cookie['name']} : \t{cookie['value']}")
    except  Exception as e:
        log.info("cookies fail!")

def presskey(key):
    presskey_relations = {
        'up':Keys.UP,
        'down':Keys.DOWN,
        'left':Keys.LEFT,
        'right':Keys.RIGHT,
        'pgup':Keys.PAGE_UP,
        'pgdn':Keys.PAGE_DOWN,
        'home':Keys.HOME,
        'end':Keys.END,
        'secape':Keys.ESCAPE,
        'tab':Keys.TAB,
        'enter':Keys.ENTER
    }#按键关系映射
    ActionChains(browser).send_keys(presskey_relations.get(key)).perform()


if __name__ == '__main__':
    init("http://bing.com.cn")
    browser.execute_script('window.open()') # 打开一个新窗口
    browser.switch_to.window(browser.window_handles[-1]) # 切换到新打开的窗口
    browser.get('https://www.163.com') # 在新窗口打开163
    browser.execute_cdp_cmd('Network.setUserAgentOverride',
                           {"userAgent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36'}) # 切换user-agent
    print(browser.execute_script('return navigator.userAgent'))
    input()